<?php
class SnapshotUtility
{
    public static function build($userId)
    {
        // flush
        $snapshot = new SnapshotKey($userId);
        $snapshot->delete();

        // build
        $targetIds = UserModel::model()->getSnapshot($userId);
        foreach($targetIds as $targetId)
        {
            $snapshot->push($targetId);
        }
    }

    public static function updatePreference($userId, $interestId, $genderId, $ageFrom, $ageTo, $cityId, $distance)
    {
        SnapshotPreferenceModel::model()->updateByPk($userId, array('interest_id' => $interestId,
                                                                    'gender_id' => $genderId,
                                                                    'age_from' => $ageFrom,
                                                                    'age_to' => $ageTo,
                                                                    'city_id' => $cityId,
                                                                    'distance' => $distance));
    }

    public static function getTarget($userId, $index)
    {
        $snapshot = new SnapshotKey($userId);
        $targetId = $snapshot->index($index);
        return UserUtility::getInfo($targetId);
    }

    public static function getTargets($userId, $start = 0, $length = 1)
    {
        $snapshot = new SnapshotKey($userId);
        $targetIds = $snapshot->range($start, $start + $length - 1);
        return UserUtility::getInfos($targetIds);
    }

    public static function play($userId, $isLike)
    {
        // remove
        $snapshot = new SnapshotKey($userId);
        $targetId = $snapshot->shift();

        // set data
        $userLike = new UserLikeModel();
        $userLike->user_id = $userId;
        $userLike->target_id = $targetId;
        $userLike->is_like = $isLike;
        $userLike->is_snapshot = 1;
        $userLike->save();
    }
}